package com.cpone.cloudweb.utils.bak;

import com.sun.crypto.provider.SunJCE;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.Security;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密
 * @author zzb
 *
 */
public class SecurityUtil
{

    public static String byteArr2HexStr(byte abyte0[])
        throws Exception
    {
        int i = abyte0.length;
        StringBuffer stringbuffer = new StringBuffer(i * 2);
        for(int j = 0; j < i; j++)
        {
            int k;
            for(k = abyte0[j]; k < 0; k += 256);
            if(k < 16)
                stringbuffer.append("0");
            stringbuffer.append(Integer.toString(k, 16));
        }

        return stringbuffer.toString();
    }

    public static byte[] hexStr2ByteArr(String s)
        throws Exception
    {
        byte abyte0[] = s.getBytes();
        int i = abyte0.length;
        byte abyte1[] = new byte[i / 2];
        for(int j = 0; j < i; j += 2)
        {
            String s1 = new String(abyte0, j, 2);
            abyte1[j / 2] = (byte)Integer.parseInt(s1, 16);
        }

        return abyte1;
    }

    public SecurityUtil()
        throws Exception
    {
        this(strDefaultKey);
    }

    public SecurityUtil(String s)
        throws Exception
    {
        encryptCipher = null;
        decryptCipher = null;
        Security.addProvider(new SunJCE());
        Key key = getKey(s.getBytes());
        encryptCipher = Cipher.getInstance("DES");
        encryptCipher.init(1, key);
        decryptCipher = Cipher.getInstance("DES");
        decryptCipher.init(2, key);
    }

    public byte[] encrypt(byte abyte0[])
        throws Exception
    {
        return encryptCipher.doFinal(abyte0);
    }

    public String encrypt(String s)
        throws Exception
    {
        return byteArr2HexStr(encrypt(s.getBytes()));
    }

    public byte[] decrypt(byte abyte0[])
        throws Exception
    {
        return decryptCipher.doFinal(abyte0);
    }

    public String decrypt(String s)
        throws Exception
    {
        return new String(decrypt(hexStr2ByteArr(s)));
    }

    private Key getKey(byte abyte0[])
        throws Exception
    {
        byte abyte1[] = new byte[8];
        for(int i = 0; i < abyte0.length && i < abyte1.length; i++)
            abyte1[i] = abyte0[i];

        SecretKeySpec secretkeyspec = new SecretKeySpec(abyte1, "DES");
        return secretkeyspec;
    }

    public static void main(String args[])
    {
        try
        {
            String s = "\u6211\u662F\u4E2D\u56FD\u4EBA";
            SecurityUtil desutil = new SecurityUtil("test");
            System.out.println("\u52A0\u5BC6\u524D\u7684\u5B57\u7B26\uFF1A" + s);
            System.out.println("\u52A0\u5BC6\u540E\u7684\u5B57\u7B26\uFF1A" + desutil.encrypt(s));
            System.out.println("\u89E3\u5BC6\u540E\u7684\u5B57\u7B26\uFF1A" + desutil.decrypt(desutil.encrypt(s)));
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
    }

	private static String strDefaultKey = "welcome";
	private Cipher encryptCipher;
	private Cipher decryptCipher;

	/**
	 * 字符串压缩
	 * 
	 * @param str
	 *            待压缩的字符串
	 * @return    返回压缩后的字符串
	 * @throws IOException
	 */
	public static String compress(String str) throws Exception {
		if (null == str || str.length() <= 0) {
			return str;
		}
		// 创建一个新的byte数组输出流
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		//使用默认缓存区大小创建新的输出流
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		// 将b.length个字节写入此输出流
		gzip.write(str.getBytes());
		gzip.close();
		// 使用指定的 charsetName，通过解码字节将缓冲区内容转换为字符串
		return out.toString("ISO-8859-1");
	}

	/**
	 * 字符串的解压
	 * 
	 * @param str
	 *            对字符串解压
	 * @return    返回解压缩后的字符串
	 * @throws IOException
	 */
	public static String unCompress(String str) throws Exception {
		if (null == str || str.length() <= 0) {
			return str;
		}
		// 创建一个新的byte数组输出流
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		//创建一个ByteArrayinputStream，使用buff作为其缓冲区数组
		ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
		//使用默认缓冲区大小创建新的输入流
		GZIPInputStream gzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n = 0;
		while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组
		// 将指定byte数组中从偏移量off开始的len个字节写入次byte数组输出流
			out.write(buffer, 0, n);
		}
		// 使用指定的chatsetName，通过解码字节将缓冲区内容转换为字符串
		return out.toString("GBK");
	}

}
